package com.qs.base.utils;

import android.os.Environment;
import android.util.Log;

import com.qs.base.data.IdentifyHistoricalEntity;
import com.qs.base.data.MyFileEntity;
import com.qs.base.utils.BaseTimeUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

/**
 * 文件处理
 *
 * @Author ltzz
 * @Date 2019/8/24
 */
public class FileUtil {
    public static String bPath = Environment.getExternalStorageDirectory().getAbsolutePath();

    /**
     * 将本地文件整理为自己想要的信息
     *
     * @param path
     * @return
     */
    public static List<IdentifyHistoricalEntity> getHistorImg(String path) {
        List<IdentifyHistoricalEntity> datas = new ArrayList<>();
        String dateStr = "";
        List<String> filePaths = new ArrayList<>();
        try {
            File file = new File(path);
            File[] files = file.listFiles();
            int one = 0;
            for (int i = files.length - 1; i >= 0; i--) {
                File file1 = files[i];
                String fileName = file1.getName();   //根据后缀判断
                if (fileName.endsWith(".jpg")) {
                    String date = BaseTimeUtils.getStringTimeOfYMD(Long.parseLong(fileName.substring(0, fileName.lastIndexOf("."))));
                    if (one == 0) {
                        dateStr = date;
                        filePaths.add(path + fileName);
                        one = 1;
                    } else {
                        if (StringUtils.equals(dateStr, date))
                            filePaths.add(path + fileName);
                        else {
                            datas.add(new IdentifyHistoricalEntity(dateStr, filePaths));
                            datas.add(new IdentifyHistoricalEntity("", filePaths));
                            dateStr = date;
                            filePaths = new ArrayList<>();
                            filePaths.add(path + fileName);
                        }
                    }
                }
            }
            if (one == 1) {
                datas.add(new IdentifyHistoricalEntity(dateStr, filePaths));
                datas.add(new IdentifyHistoricalEntity("", filePaths));
            }
        } catch (Exception e) {

        }
        return datas;
    }

    /**
     * 获取
     *
     * @param path
     * @return
     */
    public static List<MyFileEntity> getHistorTDFile(String path, int type) {
        List<MyFileEntity> datas = new ArrayList<>();
        try {
            File file = new File(path);
            File[] files = file.listFiles();
            for (int i = files.length - 1; i >= 0; i--) {
                File file1 = files[i];
                String fileName = file1.getName();
                if (type == 0) {
                    if (fileName.endsWith(".txt") || fileName.endsWith(".doc")) {
                        String s = fileName.substring(0, fileName.lastIndexOf(getCH(fileName)));
                        String dateH = BaseTimeUtils.getStringTimeOfYMD(Long.parseLong(s));
                        datas.add(new MyFileEntity(fileName, fileName.endsWith(".txt") ? "txt" : "doc", getCreateTime(file1.getAbsolutePath())));
                    }
                }
                if (type == 1) {
                    if (fileName.endsWith(".txt")) {
                        String s = fileName.substring(0, fileName.lastIndexOf(getCH(fileName)));
                        String dateH = BaseTimeUtils.getStringTimeOfYMD(Long.parseLong(s));
                        datas.add(new MyFileEntity(fileName, "txt", getCreateTime(file1.getAbsolutePath())));
                    }
                }
                if (type == 2) {
                    if (fileName.endsWith(".doc")) {
                        String s = fileName.substring(0, fileName.lastIndexOf(getCH(fileName)));
                        String dateH = BaseTimeUtils.getStringTimeOfYMD(Long.parseLong(s));
                        datas.add(new MyFileEntity(fileName, "doc", getCreateTime(file1.getAbsolutePath())));
                    }
                }
            }
        } catch (Exception e) {

        }
        return datas;
    }

    /**
     * 讲文字保存为text文档
     *
     * @param strs
     * @param path
     * @param fileName
     */
    public static void outText(List<String> strs, String path, String fileName) {
        if (strs != null) {
            try {
                String fileU = bPath + "/" + path + "/";
                File file = new File(fileU);
                if (!file.exists())
                    file.mkdirs();
                String filePath = bPath + "/" + path + "/" + fileName + ".txt";
                file = new File(filePath);
                if (!file.exists()) {
                    file.createNewFile();
                }
                FileWriter fw = new FileWriter(filePath);
                //写入数据并换行
                for (int i = 0; i < strs.size(); i++) {
                    fw.write(strs.get(i) + "\r\n");
                }
                fw.close();
                ToastUtils.showShort("保存text成功");
            } catch (Exception e) {
                e.printStackTrace();
                ToastUtils.showShort("保存失败");
            }
        }
    }

    /**
     * 讲文字保存为word文档
     *
     * @param strs
     * @param path
     * @param fileName
     */
    public static void outWord(List<String> strs, String path, String fileName) {
        if (strs != null) {
            try {
                String filePath = bPath + "/" + path + "/" + fileName + ".doc";
                File file = new File(filePath);
                if (!file.exists()) {
                    file.createNewFile();
                }
                FileWriter fw = new FileWriter(filePath);
                //写入数据并换行
                for (int i = 0; i < strs.size(); i++) {
                    fw.write(strs.get(i) + "\r\n");
                }
                fw.close();
                ToastUtils.showShort("保存word成功");
            } catch (Exception e) {
                e.printStackTrace();
                ToastUtils.showShort("保存失败");
            }
        }
    }

    /**
     * 读取文件创建时间
     *
     * @param filePath
     * @return
     */
    public static String getCreateTime(String filePath) {
        File f = new File(filePath);
        String time = "";
        if (f.exists()) {
            try {
                time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                        .format(new Date(f.lastModified()));
                KLog.e("文件文件创建时间" + time);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        KLog.e(time);
        return time;
    }

    //提取中文
    private static String getCH(String str) {
        Pattern p = null;
        Matcher m = null;
        String value = "";

        p = Pattern.compile("([\u4e00-\u9fa5]+)");
        m = p.matcher(str);
        while (m.find()) {
            value = value + m.group();
        }
        return value;
    }

    /**
     * 删除单个文件
     *
     * @param fileName 要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                KLog.e("删除单个文件" + fileName + "成功！");
                return true;
            } else {
                KLog.e("删除单个文件" + fileName + "失败！");
                return false;
            }
        } else {
            KLog.e("删除单个文件失败：" + fileName + "不存在！");
            return false;
        }
    }
}
